<template>
  <div class="flex flex-col h-full border-t border-gray-200 bg-white">
    <!-- Formatting Toolbar -->
    <div class="flex items-center px-4 pt-2 pb-1 border-b border-gray-100">
      <button class="text-gray-500 p-1 rounded hover:bg-gray-100 mr-1" title="粗体" @click="formatText('bold')">
        <i class="fas fa-bold"></i>
      </button>
      <button class="text-gray-500 p-1 rounded hover:bg-gray-100 mr-1" title="斜体" @click="formatText('italic')">
        <i class="fas fa-italic"></i>
      </button>
      <button class="text-gray-500 p-1 rounded hover:bg-gray-100 mr-1" title="代码" @click="formatText('code')">
        <i class="fas fa-code"></i>
      </button>
      <button class="text-gray-500 p-1 rounded hover:bg-gray-100 mr-1" title="链接" @click="formatText('link')">
        <i class="fas fa-link"></i>
      </button>
      <div class="h-4 w-px bg-gray-200 mx-2"></div>
      <div class="text-xs text-gray-400">快捷指令: /help, /clear, /code</div>
    </div>

    <!-- Media Buttons -->
    <div class="flex items-center px-4 pt-4 pb-2">
      <button class="text-gray-500 p-2 rounded hover:bg-gray-100">
        <i class="fas fa-microphone"></i>
      </button>
      <button class="text-gray-500 p-2 rounded hover:bg-gray-100 mx-1">
        <i class="fas fa-image"></i>
      </button>
      <button class="text-gray-500 p-2 rounded hover:bg-gray-100 mx-1">
        <i class="fas fa-paperclip"></i>
      </button>
      <button class="text-gray-500 p-2 rounded hover:bg-gray-100">
        <i class="fas fa-folder"></i>
      </button>
    </div>
    
    <!-- Message Input -->
    <div class="flex items-end flex-1 px-4 pb-4">
      <textarea 
        placeholder="输入 / 唤起AI助手" 
        class="flex-1 border border-gray-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none h-auto max-h-[calc(100%-20px)]"
        v-model="message"
        @keydown.enter.prevent="sendMessage"
        @input="handleInput"
        ref="messageInput"
        rows="1"
      ></textarea>
      <button 
        class="ml-3 px-5 py-3 bg-indigo-600 text-white rounded-full font-medium hover:bg-indigo-700 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
        @click="sendMessage"
        :disabled="isTyping || !message.trim()"
      >
        发送
      </button>
    </div>
    
    <!-- Quick Commands Popup -->
    <div v-if="showCommandPopup" class="absolute bottom-20 left-4 bg-white rounded-lg shadow-lg p-2 border border-gray-200 w-64">
      <div class="text-sm font-medium text-gray-700 mb-2">可用命令:</div>
      <div 
        v-for="cmd in filteredCommands" 
        :key="cmd.command" 
        @click="applyCommand(cmd)"
        class="p-2 hover:bg-gray-100 rounded cursor-pointer flex items-center"
      >
        <i :class="`fas ${cmd.icon} text-gray-500 mr-2`"></i>
        <div>
          <div class="font-medium">{{ cmd.command }}</div>
          <div class="text-xs text-gray-500">{{ cmd.description }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatMessageInput',
  props: {
    // Whether the AI is currently typing a response
    isTyping: {
      type: Boolean,
      default: false
    },
    
    // Current chat ID
    chatId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      message: '',
      showCommandPopup: false,
      commandPrefix: '',
      quickCommands: [
        { command: '/help', description: '显示所有可用的命令', icon: 'fa-question-circle', action: () => this.showHelpMessage() },
        { command: '/clear', description: '清除当前输入', icon: 'fa-eraser', action: () => this.clearInput() },
        { command: '/code', description: '插入代码块', icon: 'fa-code', action: () => this.insertCodeBlock() }
      ]
    }
  },
  computed: {
    filteredCommands() {
      if (!this.commandPrefix) return this.quickCommands;
      return this.quickCommands.filter(cmd => 
        cmd.command.toLowerCase().includes(this.commandPrefix.toLowerCase()));
    }
  },
  methods: {
    handleInput(event) {
      this.autoResizeTextarea(event);
      this.detectCommands();
    },
    
    detectCommands() {
      // 检测命令前缀
      const match = this.message.match(/^\/(\w*)$/);
      if (match) {
        this.commandPrefix = match[0];
        this.showCommandPopup = true;
      } else {
        this.showCommandPopup = false;
      }
    },
    
    applyCommand(command) {
      command.action();
      this.showCommandPopup = false;
    },
    
    showHelpMessage() {
      this.message = '';
      // 发送帮助信息作为系统消息
      this.$emit('send-message', {
        content: "可用命令:\n- /help: 显示此帮助信息\n- /clear: 清除当前输入\n- /code: 插入代码块",
        chatId: this.chatId,
        isSystemHelp: true
      });
    },
    
    clearInput() {
      this.message = '';
      this.resetInput();
    },
    
    insertCodeBlock() {
      this.message = "```\n// 请在这里输入代码\n```";
      this.focusWithCursorPosition(this.message.indexOf('请') - 2);
    },
    
    focusWithCursorPosition(position) {
      this.$nextTick(() => {
        const textarea = this.$refs.messageInput;
        textarea.focus();
        textarea.setSelectionRange(position, position);
      });
    },
    
    formatText(type) {
      const textarea = this.$refs.messageInput;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const selectedText = this.message.substring(start, end);
      
      let formattedText = '';
      let cursorPosition = 0;
      
      switch(type) {
        case 'bold':
          formattedText = `**${selectedText || '粗体文本'}**`;
          cursorPosition = selectedText ? start + formattedText.length : start + 2;
          break;
        case 'italic':
          formattedText = `*${selectedText || '斜体文本'}*`;
          cursorPosition = selectedText ? start + formattedText.length : start + 1;
          break;
        case 'code':
          formattedText = `\`${selectedText || '代码'}\``;
          cursorPosition = selectedText ? start + formattedText.length : start + 1;
          break;
        case 'link':
          formattedText = `[${selectedText || '链接文本'}](网址)`;
          cursorPosition = selectedText ? start + formattedText.length - 3 : start + 1;
          break;
      }
      
      this.message = this.message.substring(0, start) + formattedText + this.message.substring(end);
      
      this.$nextTick(() => {
        textarea.focus();
        if (selectedText) {
          textarea.setSelectionRange(start, start + formattedText.length);
        } else {
          textarea.setSelectionRange(cursorPosition, cursorPosition + (formattedText.length - 4));
        }
      });
    },
    
    sendMessage() {
      if (!this.message.trim() || this.isTyping) return;
      
      // Emit the message to parent component
      this.$emit('send-message', {
        content: this.message,
        chatId: this.chatId
      });
      
      // Clear input and reset height
      this.message = '';
      this.$nextTick(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.style.height = 'auto';
        }
      });
    },
    
    autoResizeTextarea(event) {
      const textarea = event.target;
      textarea.style.height = 'auto';
      
      // Get the maximum height based on container
      const container = this.$el;
      const maxHeight = container.clientHeight - 100; // Accounting for padding, buttons and toolbar
      
      textarea.style.height = Math.min(textarea.scrollHeight, maxHeight) + 'px';
    },
    
    // Method to programmatically focus the input
    focus() {
      this.$nextTick(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.focus();
        }
      });
    },
    
    // Method to reset the input
    resetInput() {
      this.message = '';
      this.$nextTick(() => {
        if (this.$refs.messageInput) {
          this.$refs.messageInput.style.height = 'auto';
        }
      });
    },
    
    // Adjust text area when container size changes
    adjustTextAreaSize() {
      this.$nextTick(() => {
        if (this.$refs.messageInput && this.$refs.messageInput.value) {
          this.autoResizeTextarea({ target: this.$refs.messageInput });
        }
      });
    }
  },
  mounted() {
    // Observe resize changes
    if (window.ResizeObserver) {
      this.resizeObserver = new ResizeObserver(() => {
        this.adjustTextAreaSize();
      });
      this.resizeObserver.observe(this.$el);
    }
    
    // 点击文档其他地方关闭命令弹窗
    document.addEventListener('click', (e) => {
      if (!this.$el.contains(e.target)) {
        this.showCommandPopup = false;
      }
    });
  },
  beforeUnmount() {
    // Clean up resize observer
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    
    // Clean up event listener
    document.removeEventListener('click', () => {});
  }
}
</script>

<style scoped>
textarea {
  min-height: 48px;
}

.absolute {
  position: absolute;
  z-index: 10;
}
</style> 